from PySide6.QtCore import QUrl, Slot, QObject
from PySide6.QtQuick import QQuickItem
from PySide6.QtQuickWidgets import QQuickWidget
from PySide6.QtWidgets import QWidget, QApplication, QVBoxLayout, QPushButton
 
 
# 槽函数类（一个承载槽函数的容器类）
class Slots(QObject):
    def __init__(self, obj):
        super(Slots, self).__init__()
        self.obj = obj
 
    @Slot(str, result=None)
    def set_text_msg(self, msg):
        # 获取qml中的Text对象
        child = self.obj.findChild(QQuickItem, "text1")
        # 获取对象属性
        p = child.property("text")
        # 设置对象属性
        child.setProperty("text", p + msg)
 
    @Slot(result=str)
    def get_text_msg(self):
        return "皎氯"
 
 
class TestQWidget(QWidget):
 
    def __init__(self, parent=None):
        super(TestQWidget, self).__init__(parent)
        self.resize(800, 300)
        # 垂直布局
        self.layout = QVBoxLayout(self)
        # OK按钮
        self.button = QPushButton("OK")
        self.button.clicked.connect(lambda: print("OK"))
        self.layout.addWidget(self.button)
 
        # QML控件
        self.qml_widget = QQuickWidget()
        # 设置缩放模式
        self.qml_widget.setResizeMode(QQuickWidget.ResizeMode.SizeRootObjectToView)
        # 向QML中传入数据（必须在setSource之前传入）
        self.qml_widget.rootContext().setContextProperty("obj", '张良')
        self.qml_widget.setSource(QUrl("test2.qml"))
        # 获取QML中的对象（必须在setSource之后）
        self.root_object: QQuickItem = self.qml_widget.rootObject()
        print(self.root_object)
        # 实例化槽函数
        self.slots = Slots(self.root_object)
        # 注入槽函数
        self.qml_widget.rootContext().setContextProperty('slots', self.slots)
 
        # 获取对象
        child: QQuickItem = self.root_object.findChild(QQuickItem, "text1")
        # 获取对象属性
        print(child.property("text"))
        
        # 加入布局
        self.layout.addWidget(self.qml_widget)
 
 
if __name__ == '__main__':
    app = QApplication([])
    widget = TestQWidget()
    widget.show()
    app.exec()